<template>
  <div class="info-card flex flex-col">
    <div
        class="flex flex-col"
        @click.stop.prevent="goDetail"
    >
      <div class="flex items-center justify-between mb-16px">
        <div class="fw-500 font-size-18px text-dark">
          {{ props.data.supplyTitle }}
        </div>
        <span
            class="font-size-12px text-#fff lh-16px py-3px px-10px border-rd-2px"
            :style="tagBgStyle"
        >{{ tagName }}</span>
      </div>
      <div class="flex items-center mb-16px font-size-14px">
        <div class="inline-flex items-center mr-20px">
          <img class="w-16px h-16px mr-3px" src="@/assets/map.svg" alt="" />
          {{ props.data?.provinceName }} {{ props.data?.cityName }}
        </div>
        <div class="inline-flex items-center">
          <img class="w-16px h-16px mr-3px" src="@/assets/time.svg" alt="" />
          <span class="text-#767676">{{
              props.data.createTime.slice(0, 16)
            }}</span>
        </div>
      </div>
      <div class="w-full h-1px bg-#D9DBE1 mb-20px"></div>
      <div class="flex flex-col font-size-14px">
        <div class="mb-16px">节点名：{{ props.data.supplyNodeName || '算力圈' }}</div>
        <template v-if="props.data.supplyType === 1">
          <div class="mb-16px">
            供电方式：<dictName
              :value="props.data.framePowerWay"
              code="power_way"
          />
          </div>
          <div class="mb-16px">供电功率：{{ props.data.framePower }}</div>
          <div class="mb-16px">机柜高度：{{ props.data.frameHeight }}</div>
          <div class="mb-16px">可租数量：{{ props.data.supplyNum }}</div>
          <div class="mb-16px">
            单价：
            <span :class="{ 'blue-text': !isLoggedIn }">
              {{ isLoggedIn ? `￥${ props.data.framePrice || ''} ${props.data.priceUnit || '个'}` : '登录后查看' }}
            </span>
          </div>
        </template>
        <template v-else-if="props.data.supplyType === 2">
          <div class="mb-16px">
            运营商：<dictName :value="props.data.bwOperator" code="operator" />
          </div>
          <div class="mb-16px">
            路由类型：<dictName
              :value="props.data.bwRouteType"
              code="route_type"
          />
          </div>
          <div class="mb-16px">
            带宽单价：
            <span :class="{ 'blue-text': !isLoggedIn }">
              {{ isLoggedIn ? `￥${ props.data.bwBandwidthPrice || ''} ${props.data.priceUnit || '个'}` : '登录后查看' }}
            </span>
          </div>
          <div class="mb-16px">
            带宽可租数量(个)：{{ props.data.bwBandwidthNum }}
          </div>
          <div class="flex justify-between">
            <span>IP可租数量(个)：{{ props.data.bwIpNum }}个</span>
            <div class="mb-16px">
              IP单价：
              <span :class="{ 'blue-text': !isLoggedIn }">
              {{ isLoggedIn ? `￥${ props.data.bwIpPrice || ''} ${props.data.priceUnit || '个'}` : '登录后查看' }}
            </span>
            </div>
          </div>
        </template>
        <template v-else-if="props.data.supplyType === 4">
          <div class="mb-16px">
            计算资源：<dictName
              :value="props.data.gpuResource"
              code="gpu_resource_type"
          />
          </div>
          <div class="mb-16px">网络架构：{{ props.data.gpuNet }}</div>
          <div class="mb-16px">
            计费模式：{{ GPU_ABILITY_TYPE_ENUM[props.data.gpuAbilityType] }}
          </div>
          <div class="mb-16px">适用场景：{{ props.data.gpuOccasion }}</div>
          <div class="flex justify-between">
            <span>拥有数量：{{ props.data.gpuNum }}</span>
            <div class="mb-16px">
              单价：
              <span :class="{ 'blue-text': !isLoggedIn }">
              {{ isLoggedIn ? `￥${ props.data.gpuPrice|| ''} ${props.data.priceUnit || '个'}` : '登录后查看' }}
            </span>
            </div>
          </div>
        </template>
        <template v-else-if="props.data.supplyType === 5">
          <div class="mb-16px">品牌：{{ props.data.brandName }}</div>
          <div class="mb-16px">型号：{{ props.data.modelName }}</div>
          <div class="mb-16px">联系人：{{ props.data.contactUser }}</div>
          <div class="mb-16px">
            联系电话：
            <span :class="{ 'blue-text': !isLoggedIn }">
                  {{ isLoggedIn ? props.data.contactUserMobile : '登录后查看' }}
                </span>
          </div>
          <div class="mb-16px">
            单价：
            <span :class="{ 'blue-text': !isLoggedIn }">
              {{ isLoggedIn ? `￥${props.data.goodsPrice || ''} ${props.data.priceUnit || '个'}` : '登录后查看' }}
            </span>
          </div>
        </template>
      </div>
    </div>
    <div class="card-footer flex items-center justify-between">
      <el-button
          v-if="props.data.supplyType === 5"
          size="mini"
          @click.stop="toggleStatus"
      >{{ props.data.status === 1 ? "下架" : "上架" }}</el-button>
      <el-button
          v-if="props.data.supplyType === 5"
          type="primary"
          size="mini"
          @click.stop="goEdit"
      >编辑</el-button>
    </div>
    <el-dialog
        v-model="addVisible"
        width="60vw"
        :title="isAdd ? '新增' : '编辑'"
        :close-on-click-modal="false"
        @close="handleClose"
    >
      <el-form
          ref="formRef"
          :model="addData"
          :rules="rules"
          label-width="100"
          class="py-16px px-32px"
      >
        <el-form-item label="供应标题" prop="supplyTitle">
          <el-input v-model=" props.data.supplyTitle" placeholder="请输入供应标题"></el-input>
        </el-form-item>
        <el-form-item label="配置参数" prop="supplyDesc">
          <el-input
              type="textarea"
              v-model=" props.data.supplyDesc"
              placeholder="请输入配置参数"
              :rows="3"

          ></el-input>
        </el-form-item>

        <el-form-item label="品牌" prop="brandName">
          <el-input v-model=" props.data.brandName" placeholder="请输入品牌"></el-input>
        </el-form-item>
        <el-form-item label="型号" prop="modelName">
          <el-input v-model=" props.data.modelName" placeholder="请输入型号"></el-input>
        </el-form-item>
        <el-form-item label="货源性质" prop="goodsType">
          <el-radio-group v-model=" props.data.goodsType">
            <el-radio :label="1">现货</el-radio>
            <el-radio :label="2">期货</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="信息大图" prop="infoPicUrl">
          <ShardUpload
              v-model="props.data.infoPicUrl"
              :limit="1"
              :fileSize="50"
              accept="image/*,video/*"
              :fileType="['png', 'jpg', 'jpeg', 'mp4', 'avi']"
              :extraTips=" props.data.infoType === 1 ? '轮播图尺寸： 1920 * 620' : ''"
              @change="handleFileChange"
              @uploadSuccess="uploadSuccess"
          />
        </el-form-item>
        <el-form-item label="销售数量" prop="goodsNumber">
          <el-input
              v-model=" props.data.goodsNumber"
              placeholder="请输入销售数量"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="goodsPrice">
          <el-input
              v-model=" props.data.goodsPrice"
              placeholder="请输入单价"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="priceUnit">
          <el-select v-model=" props.data.priceUnit" placeholder="请选择单位">
            <el-option
                v-for="option in goodsUnitOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if=" props.data.goodsType === 2" label="到货时间" prop="arriveTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model=" props.data.arriveTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择到货时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if=" props.data.goodsType === 2" label="批次量/次" prop="batchNum">
          <el-input
              v-model=" props.data.batchNum"
              placeholder="请输入每次交货的批次量"
              :maxlength="11"
              type="number"
          ></el-input>
        </el-form-item>
        <el-form-item v-if=" props.data.goodsType === 1" label="信息过期时间" prop="expireTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model=" props.data.expireTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input
              v-model=" props.data.contactUser"
              placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactUserMobile">
          <el-input
              v-model=" props.data.contactUserMobile"
              placeholder="请输入联系电话"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="交付地点" prop="goodsAddress">
          <el-input
              v-model=" props.data.goodsAddress"
              placeholder="请输入交付地点"
              :maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="confirmLoading"
            @click="handleSubmit"
        >确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  SOURCE_TYPE_ENUM,
  SOURCE_TYPE_TAG_COLOR_ENUM,
  GPU_ABILITY_TYPE_ENUM,
  REVIEW_STATUS_ENUM,
  REVIEW_STATUS_TAG_TYPE_ENUM, DICT_MAP,
} from "@/const";
import {computed, ref} from "vue";
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store';
import { inject } from 'vue';
const isAdd = ref(false);
const addVisible = ref(false);
const { list: goodsUnitOptions } = useDict(DICT_MAP.goods_price_unit);
import ShardUpload from "@/components/FileUpload/shardUpload.vue";
import {useDict, useLoading} from "@/hooks";
const { loading, setLoading } = useLoading();
const userStore = useUserStore();
const { loading: confirmLoading, setLoading: setConfirmLoading } = useLoading();
const isLoggedIn = computed(() => !!userStore.userInfo); // 确认用户是否已登录
const props = defineProps({
  data: Object,
  isCreator: Boolean,
});

const emits = defineEmits(["toggle"]);

const tagName = computed(() => SOURCE_TYPE_ENUM[props.data.supplyType]);
const tagBgStyle = computed(() => ({
  background: SOURCE_TYPE_TAG_COLOR_ENUM[props.data.supplyType],
}));

const router = useRouter();
const goDetail = () => {
  router.push({
    name: "SupplyDetail",
    query: { id: props.data.id, type: 'supply' },
  });
};

const $api = inject("$api");
const toggleStatus = async () => {
  const { id, status } = props.data;
  const { code } = await $api.supply.toggleSupply({
    id,
    status: Number(!status),
  });
  if (code === 200) {
    ElMessage.success(status ? "下架成功" : "上架成功");
    emits("toggle");
  }
};

const goEdit = () => {
  isAdd.value = false;
  addVisible.value = true;
};
const uploadSuccess = (file) => {
  if (file && file.url) {
    addData.value.infoPicUrl = file.url;
  } else {
    console.error('文件 URL 无效:', file);
  }
};

const handleFileChange = (file) => {

};

const handleSubmit = async () => {
  try {

    const requestData = {
      ...props.data,
      supplyType: 5
    };

    setLoading(true);
    const { code } = await $api.supply.updateSupply(requestData); // Pass the data as argument
    if (code === 200) {
      ElMessage.success('保存成功');
      handleClose();
      emits('refresh');
    } else {
      ElMessage.error('保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败');
  } finally {
    setLoading(false);
  }
};


const handleClose = () => {
  addVisible.value = false;
};
</script>

<style scoped>
.info-card {
  position: relative;
}

.blue-text {
  color: #2196F3; /* 蓝色 */
}

.flex {
  display: flex;
}

</style>
